﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using JXT.PrimaryKey.Batman.Core.WcfService;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Models;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Services;
using JXT.PrimaryKey.Batman.WcfService.Services.Extensions;

namespace JXT.PrimaryKey.Batman.WcfService.Services
{
    public class WcfAuthenticationAttribute : WcfServiceAttributeBase, IParameterInspector, IOperationBehavior
    {
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            //throw new NotImplementedException();
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            Authentication();
            return null;
        }

        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            //throw new NotImplementedException();
        }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            //throw new NotImplementedException();
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            //throw new NotImplementedException();
            dispatchOperation.ParameterInspectors.Add(this);
        }

        public void Validate(OperationDescription operationDescription)
        {
            //throw new NotImplementedException();
        }

        protected virtual void Authentication()
        {
            string id = ServiceEnvironment.GetAuthenticationId();
            string key = ServiceEnvironment.GetAuthenticationKey();
            if (String.IsNullOrWhiteSpace(id) || String.IsNullOrWhiteSpace(key))
                throw new ServiceAuthenticationException("must provide id and dynamic key!");
            var result = LoadService<ISystemUserService>().CheckStatus(id, key, OperationContext.Current.GetClientIp());
            if (!result)
                throw new ServiceAuthenticationException("id or dynamic error!");
        }
    }
}
